package conf

import (
	"errors"
	"flag"
	"net"
	"os"
)

type IClient interface {
	Get(string) string
	Bind(string, interface{}) error
}

var (
	_defaultClient IClient

	cfgPath string
	cfgHost string
)

var (
	ErrKeyNotFound     = errors.New("key not found")
	ErrCfgFileNotFound = errors.New("config file not found")
)

func init() {
	flag.StringVar(&cfgPath, "conf", "", "default config path")
	flag.StringVar(&cfgHost, "conf_url", os.Getenv("CONF_URL"), `config server url.`)
}

func Init() error {
	var err error
	if cfgHost == "" {
		_defaultClient, err = NewFile()
	} else {
		_defaultClient, err = NewNcs()
	}
	return err
}

func Get(key string) string {
	return _defaultClient.Get(key)
}

func Bind(key string, value interface{}) error {
	return _defaultClient.Bind(key, value)
}

// LocalIP return local IP of the host.
func localIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, address := range addrs {
		// check the address type and if it is not a loopback the display it
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}
